package main

import (
	"context"
	"fmt"
	"log"
	"math/rand"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 定义文档结构
type Metric struct {
	ID       string `bson:"_id"`
	Hostname string `bson:"hostname"`
	CPU      int    `bson:"CPU"`
	Memory   int    `bson:"memory"`
}

// 如果文档不存在则插入，否则跳过
func insertDocumentIfNotExists(collection *mongo.Collection, documentID string) error {
	// 检查文档是否已存在
	filter := bson.M{"_id": documentID}
	var existingDoc bson.M
	err := collection.FindOne(context.TODO(), filter).Decode(&existingDoc)

	if err == mongo.ErrNoDocuments {
		// 文档不存在，插入新文档
		newDoc := Metric{
			ID:       documentID,
			Hostname: documentID,
			CPU:      0,
			Memory:   2048,
		}
		_, err := collection.InsertOne(context.TODO(), newDoc)
		if err != nil {
			return fmt.Errorf("failed to insert document: %v", err)
		}
		fmt.Println("Inserted new document with ID:", documentID)
	} else if err != nil {
		return fmt.Errorf("failed to check for existing document: %v", err)
	} else {
		fmt.Println("Document already exists with ID:", documentID)
	}

	return nil
}

// 更新文档中的 CPU 字段
func updateCPUField(collection *mongo.Collection, documentID string) error {
	// 生成随机 CPU 值（模拟 CPU 负载变化）
	cpuValue := rand.Intn(100)

	// 更新 CPU 字段
	filter := bson.M{"_id": documentID}
	update := bson.M{"$set": bson.M{"CPU": cpuValue}}

	result, err := collection.UpdateOne(context.TODO(), filter, update)
	if err != nil {
		return fmt.Errorf("failed to update CPU field: %v", err)
	}

	fmt.Printf("Updated CPU field to %d for document with ID: %s (Matched: %d, Modified: %d)\n",
		cpuValue, documentID, result.MatchedCount, result.ModifiedCount)

	return nil
}

func Main(obj map[string]interface{}) map[string]interface{} {
	documentID, ok := obj["name"].(string)
	if !ok {
		documentID = "default"
	}
	msg := make(map[string]interface{})
	msg["message"] = ""
	// MongoDB 连接 URI
	uri := "mongodb://mongo-nodeport.openwhisk.svc.cluster.local:27017"
	clientOptions := options.Client().ApplyURI(uri)

	// 连接到 MongoDB
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		msg["message"] = err.Error()
		return msg
	}

	// 检查连接
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		msg["message"] = err.Error()
		return msg
	}
	fmt.Println("Connected to MongoDB!")

	// 选择数据库和集合
	database := client.Database("test")
	collection := database.Collection("task")

	// 第一次插入文档
	err = insertDocumentIfNotExists(collection, documentID)
	if err != nil {
		msg["message"] = err.Error()
		return msg
	}
	// 设置一个定时器，1分钟后触发
	timer := time.NewTimer(40 * time.Second)
	// 每隔 10 秒更新文档中的 CPU 字段
	ticker := time.NewTicker(10 * time.Second)
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			err := updateCPUField(collection, documentID)
			if err != nil {
				msg["message"] = "Failed to update CPU field:" + err.Error()
				log.Println("Failed to update CPU field:", err)
				return msg
			}
		case <-timer.C:
			fmt.Println("1 minute has passed. Stopping the program.")
			msg["message"] = "1 minute has passed. Stopping the program."
			return msg
		}
	}
}
